<template>
  <div class="c-bg-sgray c-pt20" v-if="fromOrderDetail != 1">
    <!-- 有地址 -->
    <div class="c-pb20 c-ph24">
      <div v-for="(item,index) in addressList" :key="item.addrId" class=" c-bg-white c-mb20 c-fc-xblack">
        <div class="c-ph24 c-p c-pv20 c-bd-b1" @click="clickSelectAddress(index)">
          <div class="c-fs24">
            <span>{{item.name}}</span>
            <span class="c-pl26">{{item.mobile}}</span>
          </div>
          <div class="c-pt8 c-fs20">
            <span>{{item.province}}</span>
            <span>{{item.city}}</span>
            <span>{{item.area}}</span>
            <span>{{item.address}}</span>
          </div>
          <img v-show="item.status == 1" class="img-defult-address" src="@/assets/img_defult_address.png" alt="">
        </div>
        <div class="c-flex-row c-aligni-center c-hh70 c-fs24 c-bd-b1">
          <div class="c-flex-grow1 c-w0 c-bd-r2-d2 c-h c-lh70 c-ph24" @click="clickSetDefult(index)">
            <span class="iconfont c-fs28 theme-fc" v-show="item.status != 1">&#xe692;</span>
            <span class="iconfont c-fs28 theme-fc" v-show="item.status == 1">&#xe6b1;</span>
            <span class="c-pl8" :class="item.status == 1 ? 'theme-fc':''">{{item.status == 1 ? "默认地址":"设为默认"}}</span>
          </div>
          <div class="c-ph24 c-textAlign-c c-bd-r2-d2 c-h c-lh70" @click="clickEditAddress(item.addrId)">
            <span class="iconfont c-fs28 c-fc-gray">&#xe742;</span>
            <span class="c-fc-gray">编辑</span>
          </div>
          <div class="c-ph24 c-textAlign-c c-h c-lh70" @click="clickDel(item.addrId)">
            <span class="iconfont c-fs28 c-fc-gray">&#xe6b3;</span>
            <span class="c-fc-gray">删除</span>
          </div>
        </div>
      </div>
      <loading-status-tem :dataStatus="dataStatus" noDataText="暂无收货地址，点击下方添加"></loading-status-tem>
    </div>

    <div @click="clickEditAddress('')" class="c-w100 c-hh80 c-flex-row c-flex-center c-fs30 c-fc-white theme-bg c-pf c-p-b0 c-maxw640">
      + 新增收货地址
    </div>
  </div>
  <div v-else-if="fromOrderDetail == 1 && addressDetail.length > 0" class="c-bg-sgray">
    <div class="theme-fc theme-bg-10 c-pv16 c-ph24 c-fs22" v-if="addressDetail && addressDetail.length > 1"><span class="iconfont icon-tongzhi c-fs20 c-mr12"></span>{{addressDetail.length}}个包裹已发出</div>
    <div class="c-bg-white c-ph24" v-if="addressDetail && addressDetail.length > 1">
      <my-small-tabbar
        :tabList="tabList"
        :tabIndex="tabIndex"
        :isScroll="true"
        :flexClass="''"
        :tabNameClass="'c-fs24'"
        :fontSet="{activeColor: 'c-fc-xlack c-fw-b',defaultColor: 'c-fc-gray'}"
        @changeTab="changeType"
        class="c-bd-b1-f6"
      ></my-small-tabbar>
    </div>
    <div v-if="addressDetail[tabIndex - 1]">
      <div class="c-bg-white c-ph24 c-pv24">
        <p class="c-fc-xblack c-fs20 c-fc-sblack" v-if="addressDetail[tabIndex - 1].deliverType == 3">配送方式：<span class="c-fc-xblack c-ml10">无需物流</span></p>
        <div v-if="addressDetail[tabIndex - 1].deliverType == 1">
          <p class="c-fc-xblack c-fs20 c-fc-sblack" :class="addressDetail[tabIndex - 1].deliverType == 3 ? 'c-mt20' : ''">物流状态：<span class="c-fc-xblack c-ml10">{{expressStateMap[addressDetail[tabIndex - 1].state]}}</span></p>
          <p class="c-fc-xblack c-fs20 c-fc-sblack c-mt20">配送方式：<span class="c-fc-xblack c-ml10">{{addressDetail[tabIndex - 1].shipName}}</span></p>
          <p class="c-fc-xblack c-fs20 c-fc-sblack c-mt20">物流单号：<span class="c-fc-xblack c-ml10">{{addressDetail[tabIndex - 1].shipNo}}</span><span class="c-ml20 c-fs18 c-fc-xblack c-pv6 c-ph18 c-br18 c-bg-f2" @click="copyText(addressDetail[tabIndex - 1].shipNo)">复制</span></p>
        </div>
        <div class="c-mt24 c-flex-row c-aligni-center c-flexw-wrap">
          <div v-for="(img, imgIndex) in addressDetail[tabIndex - 1].goods" :key="imgIndex" class="c-hh80 c-ww80 c-br8 c-text-hidden" :class="addressDetail[tabIndex - 1].goods.length % 6 == 0 ? '' : 'c-mr20'">
            <img :src="$addXossFilter(img.avatar)" class="c-w100 c-h c-object-fit-cover">
          </div>
        </div>
      </div>
      <div class="c-mt12 c-bg-white" v-if="addressDetail[tabIndex - 1].deliverType == 1">
        <div class="c-pl4 c-pt30 c-pr24" v-if="addressDetail[tabIndex - 1].traces && addressDetail[tabIndex - 1].traces.length > 0">
          <div class="c-flex-row c-aligni-start c-pb44 c-p" v-for="(item, index) in addressDetail[tabIndex - 1].traces" :key="index">
            <div class="c-ww80 c-hh28 c-flex-shrink0 c-flex-row c-flex-center" :class="index == (addressDetail[tabIndex - 1].traces.length - 1) ? '' : 'border'">
              <i class="c-hh16 c-ww16 c-brp50 c-p c-pz10" :class="index == 0 ? 'theme-bg' : 'c-bg-ccc'"></i>
            </div>
            <div :class="index == 0 ? 'c-fc-xblack' : 'c-fc-gray'">
              <p class="c-fs20 c-lh28">{{item.AcceptTime}}</p>
              <p class="c-fs20 c-mt12" v-html="numberTransformTel(item.AcceptStation)"></p>
            </div>
          </div>
        </div>
        <loading-status-tem :noData="addressDetail[tabIndex - 1] && !addressDetail[tabIndex - 1].traces" :noDataTextClass="'c-fs24 c-fc-sgray c-pb120'" noDataText="暂无物流信息"></loading-status-tem>
      </div>
    </div>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import { utilJs } from "@/utils/common.js";
let pageIndex = 1;
let goId = '';
export default {
  name: "AddressList",
  components: {
    loadingStatusTem,
    MySmallTabbar
  },
  props: {
    fromPage:{
      type:String,
      default:'SHOP'
    }
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      addressList: [],
      delAddressId: "",
      dataStatus: 'HAS_MORE_DATA',
      fromOrderDetail: 0,
      addressDetail: [],
      tabList: [], // 包裹列表
      tabIndex: 1, // 包裹索引
      expressStateMap: { // 物流状态
        '0': '暂无物流信息',
        '1': '已揽收',
        '2': '在途中',
        '3': '已签收',
        '4': '问题件'
      }
    };
  },
  created() {
    if (this.fromPage != 'SHOP') {
      return;
    }
    utilJs.appShare(this);
  },
  mounted() { },
  computed: {
    // 字符串提取电话并用特殊样式、并且能拨打号码
    numberTransformTel() {
      return function(str) {
        let match = str.match(/((((13[0-9])|(15[^4])|(18[0,1,2,3,5-9])|(17[0-8])|(147))\d{8})|((\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}))?/g); // 匹配固话和移动电话
        let matchList = match.filter(item => item.length > 0);
        let telList = [];
        matchList.forEach(item => { // 电话去重
          if (telList.indexOf(item) == -1) {
            telList.push(item)
          }
        })
        telList.forEach(item => {
          let domTel = '<a class="theme-fc" href="tel:' + item + '">' + item + '</a>';
          let reg = new RegExp(item, "g"); // 设置正则，用正则替换字符串中多个相同电话号码的位置
          str = str.replace(reg, domTel);
        })
        return str
      }
    }
  },
  methods: {
    // 切换包裹
    changeType(tabIndex) {
      this.tabIndex = tabIndex;
    },
    clickSelectAddress(index) {
      localStorage.setItem(
        "AddressInfo",
        JSON.stringify(this.addressList[index])
      );
      localStorage.setItem("SelectAddress", true);
      if (this.fromPage != 'SHOP') {
        this.$emit('chooseAddress')
        return;
      }
      this.$router.go(-1);
    },
    onConfirmDel(e) {
      //删除确认
      utilJs.postMethod(
        global.apiurl + "address/delete",
        { addrId: this.delAddressId },
        res => {
          this.$showCjToast({
            text: "删除成功",
            type: "success",
            time: 1000
          });
          pageIndex = 1;
          this.getAddressList();
        }
      );
    },
    clickSetDefult(itemIndex) {
      //设置默认地址
      if (this.addressList[itemIndex].status != 1) {
        //不是默认地址，点击设置为默认地址
        utilJs.postMethod(
          global.apiurl + "address/setDefault",
          { addrId: this.addressList[itemIndex].addrId },
          res => {
            this.$showCjToast({
              text: "设置成功",
              type: "success",
              time: 1000
            });
            pageIndex = 1;
            this.getAddressList();
            localStorage.setItem(
              "AddressInfo",
              JSON.stringify(this.addressList[itemIndex])
            );
            localStorage.setItem("SelectAddress", true);
            if (this.fromPage != 'SHOP') {
              this.$emit('chooseAddress')
              return;
            }
          }
        );
      }
    },
    clickEditAddress(addressId) {
      if (this.fromPage != 'SHOP') {
        this.$emit('chooseAddressEdit', addressId)
        return;
      }
      if (addressId !== "") {
        this.$routerGo(this, "push", {
          path: "/mall/shippingAddress/addressInfo",
          query: { AddressId: addressId }
        });
      } else {
        this.$routerGo(this, "push", { path: "/mall/shippingAddress/addressInfo" });
      }
    },
    clickDel(addressNo) {
      this.delAddressId = addressNo;
      let that = this;
      that.$cjConfirm({
          title:'删除提示',
          titleCenter: true, //标题是否居中
          message: '确定要删除该地址吗？',
          messageCenter: true, //内容是否居中
          showMasker: true, //是否显示透明背景
          clickCloseModal: true, //是否点击透明背景关闭弹窗
          showCancelButton: true, //是否显示取消按钮
          onConfirm() {
            that.onConfirmDel();
          },
        })
    },
    //获取地址列表
    getAddressList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(global.apiurl + "address?page=" + pageIndex, res => {
        if (pageIndex == 1) {
          this.addressList = res.address.data;
        } else {
          this.addressList = [...this.addressList, ...res.address.data];
        }
        if (res.address.to * 1 == res.address.total * 1) {
          this.dataStatus = res.address.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          pageIndex++;
        }
      },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        });
    },
    // 获取地址详情
    getAddressDetail() {
      utilJs.getMethod(global.apiurl + "goodsOrders/getExpressInfo?goId=" + goId, res => {
        this.addressDetail = res || [];
        this.addressDetail.forEach((item, index) => {
          let data = {
            index: index + 1,
            title: '包裹' + (index + 1)
          }
          this.tabList.push(data);
        });
      }, failRes => {});
    },
    // 刷新快递鸟去准确的请求到数据
    clearLogistic() {
      utilJs.postMethod(global.apiurl + "goodsOrders/setLogistic", {goId: goId}, res => {
        setTimeout(() => {
          this.getAddressDetail();
        }, 1000)
      }, failRes => {});
    },
    // 复制
    copyText(text) {
      utilJs.copyText(text);
    },
    //分享
    wechatShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/?refereeId=" +
        localStorage.getItem("userId");
      utilJs.wechatConfig(shareUrl, "", "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      var shareUrl =
        window.location.href.split("#")[0] +
        "#/?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("", "", shareUrl, "");
    },
    windowScrollFunction: function () {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.addressList.length > 0) {
          this.getAddressList();
        }
      });
    }
  },
  activated() {
    this.fromOrderDetail = this.$route.query.fromOrderDetail;
    this.tabList = [];
    this.tabIndex = 1;
    if (this.fromOrderDetail == 1) {
      setDocumentTitle("物流详情");// eslint-disable-line
      goId = this.$route.query.goId;
      this.addressDetail = [];
      // this.getAddressDetail();
      this.clearLogistic();
    } else {
      if (this.fromPage == 'SHOP') {
        setDocumentTitle("选择收货地址");
      }
      pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.addressList = [];
      this.getAddressList();
    }
    if (this.fromPage == 'SHOP') {
      window.addEventListener('scroll', this.windowScrollFunction);
      this.wechatShare();
    }
  },
  deactivated() {
    window.removeEventListener('scroll', this.windowScrollFunction);
  },
  beforeRouteLeave(to, from, next) {
    if (!['/mall/shopSettlement/shopSettlement', '/mall/shippingAddress/addressInfo', '/homePage/live/liveRoom', '/homePage/live/liveVerticalRoom', '/homePage/marketing/winningRecord'].includes(to.path)) {
      //直播领奖跳转
      this.$store.commit("live/setPrizeInfo", null);
    }
    next();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.img-defult-address {
  position: absolute;
  top: 0.5rem;
  right: 0.6rem;
  width: 2rem;
  height: 2rem;
}
.borderDash::before{
  position: absolute;
  content: "";
  left: 1rem;
  top: 0.25rem;
  border-left: 1px dashed #e6e6e6;
  height: calc(100% - 0.1rem);
}
.border::before{
  position: absolute;
  content: "";
  left: 1rem;
  top: 0.25rem;
  border-left: 1px solid #e6e6e6;
  height: calc(100% - 0.1rem);
}
</style>
